package org.dtrd.modules.device.service.impl;

import cn.hutool.http.HttpUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.dtrd.common.api.vo.Result;
import org.dtrd.common.util.CheckUtil;
import org.dtrd.config.system.Constant;
import org.dtrd.config.system.SystemState;
import org.dtrd.modules.achievement.service.IDtrdEntRdSigninRecordService;
import org.dtrd.modules.device.config.DeviceConstant;
import org.dtrd.modules.device.config.DeviceConstant.DeviceBrand;
import org.dtrd.modules.device.config.DeviceConstant.DeviceCategory;
import org.dtrd.modules.device.config.XtyApiConfig;
import org.dtrd.modules.device.entity.bean.xty.XtyBaseResponse;
import org.dtrd.modules.device.entity.bean.xty.XtyNotifyStatusResponse;
import org.dtrd.modules.device.entity.bean.xty.XtySugarRecord;
import org.dtrd.modules.device.entity.bean.xty.XtySugarResponse;
import org.dtrd.modules.device.entity.po.DtrdEntRdDevice;
import org.dtrd.modules.device.entity.po.DtrdEntRdXty;
import org.dtrd.modules.device.entity.request.BindDeviceRequest;
import org.dtrd.modules.device.entity.request.XtySugarRecordRequest;
import org.dtrd.modules.device.mapper.DtrdEntRdXtyMapper;
import org.dtrd.modules.device.service.IDtrdEntRdDeviceService;
import org.dtrd.modules.device.service.IDtrdEntRdXtyService;
import org.dtrd.modules.device.util.XtyDataUtil;
import org.dtrd.modules.record.entity.po.DtrdEntRdSigninSugarValue;
import org.dtrd.modules.record.service.impl.SugarRecordServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

/**
 * @author 萧
 * @date 2021-09-01 00:02:01
 **/
@Service
@DS("multi-datasource1")
@Slf4j
public class DtrdEntRdXtyServiceImpl extends ServiceImpl<DtrdEntRdXtyMapper, DtrdEntRdXty> implements IDtrdEntRdXtyService {

    @Autowired
    private SugarRecordServiceImpl sugarRecordService;

    @Autowired
    private IDtrdEntRdSigninRecordService signinRecordService;

    @Autowired
    private IDtrdEntRdDeviceService deviceService;

    @Override
    public Result<?> bindDevice(BindDeviceRequest request) {
        if (DeviceConstant.BindState.isBind(request.getOperation())) {
            return doBind(request);
        } else {
            return doUnbind(request);
        }
    }

    @Override
    public DtrdEntRdXty getBindRecord(Integer patientId) {
        return patientId == null ? null : baseMapper.selectRecordByCondition(patientId, null, DeviceConstant.BindState.BIND.getState());
    }

    private Result<?> doBind(BindDeviceRequest request) {
        // 查询用户绑定记录
        DtrdEntRdXty recordByPatientId = baseMapper.selectRecordByCondition(request.getPatientId(), null, DeviceConstant.BindState.BIND.getState());
        // 查询设备关联记录
        DtrdEntRdXty recordBySn = baseMapper.selectRecordByCondition(null, request.getDeviceSn(), DeviceConstant.BindState.BIND.getState());
        if (recordByPatientId == null && recordBySn == null) {
            // 用户未曾绑定设备 设备未曾绑定用户
            // 完成绑定
            saveRecord(request.getPatientId(), request.getDeviceSn());
            return Result.OK(SystemState.ResponseState.STATE_SUCCESS.getMsg());
        } else if (recordByPatientId != null && recordBySn != null) {
            // 用户已绑定设备 设备已绑定用户
            if (recordByPatientId.getDataId().equals(recordBySn.getDataId())) {
                // 判断用户与设备关联一致
                //不作处理返回成功
                return Result.OK(SystemState.ResponseState.STATE_SUCCESS.getMsg());
            } else {
                return Result.error(SystemState.ResponseState.STATE_DATA_ERROR.getCode(), SystemState.ResponseState.STATE_DATA_ERROR.getMsg());
            }
        } else {
            // 设备已绑定 或者 用户已绑定
            // 返回错误信息
            return Result.error(SystemState.ResponseState.STATE_OPERATION_FAILURE.getCode(), SystemState.ResponseState.STATE_OPERATION_FAILURE.getMsg());
        }
    }

    private Result<?> doUnbind(BindDeviceRequest request) {
        DtrdEntRdXty record = baseMapper.selectRecordByCondition(request.getPatientId(), request.getDeviceSn(), DeviceConstant.BindState.BIND.getState());
        if (record != null) {
            // 查询当前关联状态 执行解绑
            record.setDeviceBindState(DeviceConstant.BindState.UNBIND.getState());
            baseMapper.updateById(record);
        }
        return Result.OK(SystemState.ResponseState.STATE_SUCCESS.getMsg());
    }

    private void saveRecord(Integer patientId, String deviceSn) {
        DtrdEntRdXty entity = new DtrdEntRdXty();
        entity.setCreateTime(new Date());
        entity.setUserId(patientId);
        entity.setDeviceSn(deviceSn);
        entity.setDeviceBindState(DeviceConstant.BindState.BIND.getState());
        baseMapper.insert(entity);
    }

    @Override
    public void onDataUpload(String msgId, String msgType, String content) {
        if (XtyApiConfig.MsgType.isSugarTest(msgType)) {
            log.info("DtrdEntRdXtyServiceImpl.onDataUpload.[msgId, msgType, content " + content);
            try {
                List<XtySugarRecord> recordList = com.alibaba.fastjson.JSONObject.parseArray(content, XtySugarRecord.class);
                log.info("DtrdEntRdXtyServiceImpl.onDataUpload.[msgId, msgType, content] recordList = " + recordList);
                if (CheckUtil.isNotEmpty(recordList)) {
                    String deviceImei = recordList.get(0).getDeviceImei();
//                    DtrdEntRdXty recordBySn = baseMapper.selectRecordByCondition(null, deviceImei, DeviceConstant.BindState.BIND.getState());
                    DtrdEntRdDevice recordBySn = deviceService.selectOntByDeviceSnAndDeviceType(deviceImei, DeviceBrand.XTY.getBrand(), DeviceCategory.BLOODSUGAR.getCategory());
                    if (recordBySn != null) {
                        // 查询设备绑定记录得到对应用户ID
                        Integer userId = recordBySn.getUserId();
                        sugarRecordService.saveXtySugarRecord(recordList, userId);

                        //取最后一条 关联打卡记录
                        XtySugarRecord xtySugarRecord = recordList.get(recordList.size() - 1);
                        DtrdEntRdSigninSugarValue sugarValue = sugarRecordService.getXtySugarRecord(userId, Constant.SugarSourceType.SOURCE_XTY.getType(), xtySugarRecord.getCreateTime(), xtySugarRecord.getTimeType(), xtySugarRecord.getSugar());
                        log.info("DtrdEntRdXtyServiceImpl.onDataUpload.[msgId, msgType, content] sugarValue= " + sugarValue);
                        if (sugarValue != null) {
                            signinRecordService.saveSigninRecord(sugarValue.getDataId(), userId, Constant.RecordType.SUGAR.getType(), xtySugarRecord.getTimeType(), null);
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public String onXtyConfirm(String nonce, String timestamp, String signature, String echostr) {
        if (XtyDataUtil.checkSignature(timestamp, nonce, signature)) {
            // 校验签名
            return echostr;
        } else {
            return "校验失败";
        }
    }

    @Override
    public XtyBaseResponse activeXtyPush() {
        String response = doXtyRequest(XtyApiConfig.RequestMethod.NOTIFYACTIVE.getMethod(), null);
        log.info("DtrdEntRdXtyServiceImpl.activeXtyPush.[] response=" + response);
        return response == null ? null : (XtySugarResponse) JSONObject.toBean(JSONObject.fromObject(response), XtySugarResponse.class);
    }

    @Override
    public XtyBaseResponse closeXtyPush() {
        String response = doXtyRequest(XtyApiConfig.RequestMethod.NOTIFYCLOSE.getMethod(), null);
        log.info("DtrdEntRdXtyServiceImpl.closeXtyPush.[] response=" + response);
        return response == null ? null : (XtySugarResponse) JSONObject.toBean(JSONObject.fromObject(response), XtySugarResponse.class);
    }

    @Override
    public XtyNotifyStatusResponse getXtyStatus() {
        String response = doXtyRequest(XtyApiConfig.RequestMethod.NOTIFYSTATUS.getMethod(), null);
        log.info("DtrdEntRdXtyServiceImpl.getXtyStatus.[] response=" + response);
        return response == null ? null : (XtyNotifyStatusResponse) JSONObject.toBean(JSONObject.fromObject(response), XtyNotifyStatusResponse.class);
    }

    @Override
    public XtySugarResponse getXtySugarRecord(XtySugarRecordRequest request) {
        String response = doXtyRequest(XtyApiConfig.RequestMethod.SUGARTEST.getMethod(), JSONObject.fromObject(request).toString());
        log.info("DtrdEntRdXtyServiceImpl.getXtySugarRecord.[request] response=" + response);
        return response == null ? null : (XtySugarResponse) JSONObject.toBean(JSONObject.fromObject(response), XtySugarResponse.class);
    }

    private String doXtyRequest(String method, String jsonParams) {
        try {
            String url = XtyDataUtil.jointUrl(method, jsonParams);
            log.info("DtrdEntRdXtyServiceImpl.doXtyRequest.[method, jsonParams] url=" + url + "; jsonparams=" + jsonParams);
            return HttpUtil.post(url, new JSONObject().toString());
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

}
